package com.cuiweiyou.bluemesh.ui;

import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;

import com.cuiweiyou.bluemesh.R;
import com.cuiweiyou.bluemesh.base.ExitActivity;
import com.cuiweiyou.bluemesh.bluetooth.BluetoothMaster;
import com.cuiweiyou.bluemesh.bluetooth.LightMaster;
import com.cuiweiyou.bluemesh.model.EventDeviceModel;
import com.cuiweiyou.bluemesh.model.EventLightModel;
import com.cuiweiyou.bluemesh.model.LightModel;
import com.cuiweiyou.bluemesh.util.NicknameSqlUtil;
import com.cuiweiyou.bluemesh.util.NotificationUtil;
import com.cuiweiyou.bluemesh.util.PermissionTool;
import com.cuiweiyou.bluemesh.util.SPDataUtil;
import com.cuiweiyou.bluemesh.util.WriteListUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.Iterator;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class MainActivity extends ExitActivity {

    @BindView(R.id.hometypeSwitch)
    Switch hometypeSwitch;

    @BindView(R.id.noteWriteListButtonView)
    View noteWriteListButtonView;

    @BindView(R.id.noteWriteListTextView)
    TextView noteWriteListTextView;

    @BindView(R.id.groupTabLayout)
    TabLayout groupTabLayout;

    @BindView(R.id.groupViewPager)
    ViewPager groupViewPager;

    GroupCommAdapter groupCommAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
        EventBus.getDefault().register(this);

        initView();
        initBlue();
    }

    @Override
    public int whenAppExit() {
        if (SPDataUtil.getInstance().isHometype()) { // 回家模式不真正退出
            return 1;
        }

        LightMaster.getInstance().release();
        BluetoothMaster.getInstance().release();
        EventBus.getDefault().unregister(this);
        return 0;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == PermissionTool.FLAG_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS) {
            boolean ignoringBatteryOptimizations = PermissionTool.isIgnoringBatteryOptimizations(this);
            if (ignoringBatteryOptimizations) {
                settingHometype(true); // onActivityResult。开启了非省电
            } else {
                Toast.makeText(this, "授权始终后台运行才可以使用[回家模式]", Toast.LENGTH_SHORT).show();
            }
        }
    }

    @OnClick(R.id.hometypeButtonView)
    public void onHometypeButtonClicked() {
        if (!hometypeSwitch.isChecked()) {
            boolean ignoringBatteryOptimizations = PermissionTool.isIgnoringBatteryOptimizations(this);
            if (!ignoringBatteryOptimizations) {
                PermissionTool.requestIgnoreBatteryOptimizations(this);
            } else {
                settingHometype(true); // onHometypeButtonClicked，开启
            }
        } else {
            settingHometype(false); // onHometypeButtonClicked，关闭
        }
    }

    @OnClick(R.id.noteWriteListButtonView)
    public void onNoteWriteListButtonClicked() {
        WriteListUtil.startAutoRunSettingActivity(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void onDeviceEvent(EventDeviceModel model) { // 收到设备列表刷新
        if (SPDataUtil.getInstance().isHometype()) { // 收到设备列表刷新，判断回家模式
            Map<String, List<LightModel>> map = NicknameSqlUtil.getInstance().queryAll(); // 获取全部的组名，用于开关灯
            Iterator<String> iterator = map.keySet().iterator();
            while (iterator.hasNext()) {
                String group = iterator.next();
                LightMaster.getInstance().openOrCloseAllLight(group, true);
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void onLightEvent(EventLightModel model) { // 设备状态刷新
        //if (0 == model.getFlag()) {
        //    Toast.makeText(this, "没有设备", Toast.LENGTH_SHORT).show();
        //    return;
        //} else if (-1 == model.getFlag()) {
        //    Toast.makeText(this, "没有设备在线", Toast.LENGTH_SHORT).show();
        //    return;
        //}

        if (SPDataUtil.getInstance().isHometype()) { // 到家了，关闭回家模式
            settingHometype(false); // 到家了，关闭回家模式
        }
    }

    private void initView() {
        boolean isHometype = SPDataUtil.getInstance().isHometype(); // initView
        settingHometype(isHometype); // initView

        groupTabLayout.setupWithViewPager(groupViewPager);

        groupCommAdapter = new GroupCommAdapter(getSupportFragmentManager());
        groupViewPager.setAdapter(groupCommAdapter);
        groupCommAdapter.setGroup(NicknameSqlUtil.getInstance().queryAll(), onBluetoothProcessingListener); // 初始化UI，加载曾经的设备
    }

    private void initBlue() {
        Map<String, List<LightModel>> map = NicknameSqlUtil.getInstance().queryAll(); // 获取全部的组名，开始扫描
        BluetoothMaster.getInstance().initDeviceMap(map);
        Iterator<String> iterator = map.keySet().iterator();
        while (iterator.hasNext()) {
            String group = iterator.next();
            BluetoothMaster.getInstance().scan(group);
        }
    }

    private void settingHometype(boolean isHometype) {
        SPDataUtil.getInstance().saveHometype(isHometype);
        hometypeSwitch.setChecked(isHometype);

        if (isHometype) {
            noteWriteListButtonView.setVisibility(View.VISIBLE);
            noteWriteListTextView.setText("点击操作：" + WriteListUtil.getNote());

            NotificationUtil.getInstance().makeNotification();
        } else {
            noteWriteListButtonView.setVisibility(View.GONE);

            NotificationUtil.getInstance().clearAllNotification();
        }
    }

    private OnBluetoothProcessingListener onBluetoothProcessingListener = new OnBluetoothProcessingListener() {
        @Override
        public void OnBluetoothProcessingStart() {
            showProgressDialog();
        }

        @Override
        public void OnBluetoothProcessingFinish() {
            dismissProgressDialog();
        }
    };
}
